//
//  UIWindow+Lock.m
//  HuShengDai
//
//  Created by 李亚川 on 17/5/16.
//  Copyright © 2017年 李亚川. All rights reserved.
//

#import "UIWindow+Lock.h"


@interface __OpaqueWindowLocker : NSObject
{
    NSUInteger __lockCount;
    UIActivityIndicatorView *_indicator;
    UIWindow *_lockerWindow;
    
    //李亚川
    UIWindow *_noLockerWindow;
}

+ (instancetype)locker;
- (void)lock;
- (void)unlock;
@end


@implementation __OpaqueWindowLocker

+ (instancetype)locker{
    
    static __OpaqueWindowLocker *__locker;
    @synchronized (self) {
        if (!__locker) {
            __locker = [[self alloc] init];
        }
        return __locker;
    }
}

- (id)init{
    
    self = [super init];
    if (self) {
        _lockerWindow = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
        _indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        [_lockerWindow addSubview:_indicator];
        [_indicator setCenter:_lockerWindow.center];
        _lockerWindow.backgroundColor = [UIColor clearColor];//[UIColor colorWithRed:0.5 green:0.5 blue:0.5 alpha:0.5];
        _lockerWindow.hidden = YES;
        _lockerWindow.windowLevel = UIWindowLevelAlert;
    }
    return self;
}

- (void)lock{
    
    @synchronized (self) {
        if (++__lockCount == 1) {
            dispatch_async(dispatch_get_main_queue(), ^{
                _lockerWindow.hidden = NO;
                [_indicator startAnimating];
            });
        }
    }
}

- (void)unlock{
    
    @synchronized (self) {
        if (__lockCount>0 && --__lockCount==0) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [_indicator stopAnimating];
                _lockerWindow.hidden = YES;
            });
        }
    }
}

@end






@implementation UIWindow (Lock)

+ (instancetype)mainWindow{
    return [[UIApplication sharedApplication] keyWindow];
}

+ (void)lock{
    [[__OpaqueWindowLocker locker] lock];
}

+ (void)unlock{
    [[__OpaqueWindowLocker locker] unlock];
}

+ (UIView *)keyboard{
    NSArray *windows = [[UIApplication sharedApplication] windows];
    Class UITextEffectsWindow = NSClassFromString(@"UITextEffectsWindow");
    Class UIPeripheralHostView = NSClassFromString(@"UIPeripheralHostView");
    for (int i=(int)windows.count-1; i>=0; i--) {
        UIWindow *iter = windows[i];
        if ([iter isKindOfClass:UITextEffectsWindow]) {
            if ([UIDevice currentDevice].systemVersion.floatValue >= 8 ) {
                if (iter.subviews.count == 1 && [iter.subviews.firstObject subviews].count==1) {
                    return [iter.subviews.firstObject subviews].firstObject;
                }
            } else {
                for (UIView *sub in iter.subviews) {
                    if ([sub isKindOfClass:UIPeripheralHostView]) {
                        return sub;
                    }
                }
            }
        }
    }
    return nil;
}


@end
